#    Copyright 2008, 2009 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.

#************************BEGIN Add Include Files to Path************************
import sys
IncludePath="/opt/coopgis/djangoproject/include"
if(not IncludePath in sys.path):
    sys.path.append(IncludePath)


    
#************************END   Add Include Files to Path************************
from django.contrib.gis.geos import *
import os, time, psycopg2, datetime

#********************Setup psycopg2 and django section********************
PathDjangoRoot="/opt/coopgis/"
if(not PathDjangoRoot in sys.path):
    sys.path.append(PathDjangoRoot)
from django.core.management import setup_environ
import djangoproject.settings
setup_environ(djangoproject.settings)
from djangoproject.models import *
from django.contrib.gis.geos import GEOSGeometry
import COOPGIS_Ajax, COOPGIS_DynamicTemplate, COOPGIS_FormMisc, COOPGIS_GPS, COOPGIS_Misc, COOPGIS_ReportLab, COOPGIS_String, COOPGIS_Update
import COOPGIS_ReportLabStakerReport
from django.db import transaction
#********************Setup psycopg2 and django section********************

#import AMR
#import CIS

import django.db

InputFileName='/opt/coopgis/djangoproject/RawAMR.py'
OutputFileName='/opt/coopgis/djangoproject/AMR.py'
Using="AMR"

import AMR
InputFile=open(InputFileName, 'r')
OutputFile=open(OutputFileName, 'w')

Rows=InputFile.readlines()
FirstAttributeRowIndicator=False
TableNameDict={}
InMemoryList=[]
for row in Rows:
    InMemoryList.append(row)
InputFile.close()

#Preprocess the list, putting the table names into TableNameDict (keys are class names)
for row in InMemoryList:
    if(row[:5] == 'class'):
        Key=row[5:row.find('(')]
    if("db_table = u'" in row):
        Start=row.find("'") + 1
        End=row[Start:].find("'")
        TableNameDict[Key] = row[Start:][:End]

ListOfClasses=[]

#Process the rows,putting the results intoa List in the format [[RowCount, ClassName, Rows],[RowCount, ClassName, Rows]...]        
TempList=[]
for row in InMemoryList:
    if(row[:5] == 'class'):
        TempList=[]
        FirstAttributeRowIndicator=True
        Cursor=django.db.connections['amr'].cursor()
        ClassName=row[5:row.find('(')]
        print ClassName
        Cursor.execute('select count(*) from ' + TableNameDict[ClassName] + ';')
        RowCount=Cursor.fetchall()[0][0]
        TempList.append('#' + ClassName.strip() + ' had ' + str(RowCount) + ' rows.\n')
        TempList.append(row)
    elif(FirstAttributeRowIndicator):
        FirstAttributeRowIndicator=False
        TempList.append("    using = '" + Using + "'\n")  
        if('max_length=' in row or 'null=' in row or 'decimal_places=' in row or 'blank=' in row):
            TempList.append(row[:row.find('(')+1] + 'primary_key=True, ' + row[row.find('(')+1:])
        else:
            TempList.append(row[:row.find('(')+1] + 'primary_key=True' + row[row.find('(')+1:])
    elif('db_table = ' in row):
        TempList.append(row)
        TempList.append("        app_label='djangoproject'\n")
        ListOfClasses.append([RowCount, ClassName.strip(), TempList])
        TempList=[]
    else:
        TempList.append(row)
        


OutputFile.write("""#    Copyright 2011 Tri-County Electric Cooperative, St. Matthews, South Carolina
#    This file is part of COOPGIS.
#    COOPGIS is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#    COOPGIS is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#    You should have received a copy of the GNU General Public License
#    along with COOPGIS.  If not, see <http://www.gnu.org/licenses/>.


import os, csv, shutil, datetime, time, reportlab
from django.contrib.gis.db import models
from django.http import HttpResponse
from django.contrib import admin""")


ListOfClasses.sort(key=lambda i: i[1])

for row in ListOfClasses:
    if(row[0] == 0):
        continue
    OutputFile.write('\n')
    for i in row[2]:
        OutputFile.write(i)

OutputFile.write("""\n#******************************************************
#******************************************************
#******************************************************
#Entries Below this point had 0 rows at the time the models file was created.\n
#******************************************************
#******************************************************
#******************************************************\n""")


for row in ListOfClasses:
    if(row[0] > 0):
        continue
    OutputFile.write('\n')
    for i in row[2]:
        OutputFile.write(i)


OutputFile.close()


